package com.ocean.core.util.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.ocean.core.exception.verify.ApplicationException;
import com.ocean.core.util.QRCodeUtil;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付宝支付
 *
 * @author zhang
 * @since 2023/11/4
 */
@Service
public class AlipayService {

    private final AlipayProperties alipayProperties;

    public AlipayService(AlipayProperties alipayProperties) {
        this.alipayProperties = alipayProperties;
    }

    public String generateQrCode(String orderId, BigDecimal amount) throws AlipayApiException, IOException {
        String notifyUrl = alipayProperties.getNotifyUrl();

        // 创建AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayProperties.getGatewayUrl(),
                alipayProperties.getAppId(), alipayProperties.getPrivateKey(),
                alipayProperties.getFormat(), alipayProperties.getCharset(),
                alipayProperties.getAlipayPublicKey(), alipayProperties.getSignType());

        // 创建预创建请求对象
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        model.setOutTradeNo(orderId);
        model.setTotalAmount(amount.toString());
        model.setSubject("在海洋商城购买");
        model.setTimeoutExpress("15m");
        request.setBizModel(model);
        request.setNotifyUrl(notifyUrl);

        // 发送请求并获取响应
        AlipayTradePrecreateResponse alipayTradePrecreateResponse = alipayClient.execute(request);
        if (alipayTradePrecreateResponse.isSuccess()) {
            String qrCode = alipayTradePrecreateResponse.getQrCode();
            return QRCodeUtil.createQrCode(qrCode, 200, 200);
        } else {
            throw new ApplicationException("生成支付宝二维码失败：" + alipayTradePrecreateResponse.getSubMsg());
        }
    }

    public boolean checkSignIn(String sign, String content) {
        try {
            return AlipaySignature.rsaCheck(content, sign, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return false;
    }

    public Map<String, String> paramsToMap(HttpServletRequest request) throws UnsupportedEncodingException {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }
}
